import { getProfile, login } from '@/api/user'
// import { resetRouter } from '@/router'
import { getToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

const state = {
  token: getToken() || '',
  // 用户信息
  userInfo: {}
}

const mutations = {
  // 用户token 值
  setToken(state, newToken) {
    state.token = newToken
    // 存入本地
    setToken(newToken)
  },
  // 用户信息
  setUserinfo(state, userInfo) {
    state.userInfo = userInfo
  }
}

const actions = {
  // 退出
  logout(cxt) {
    cxt.commit('setToken', '')
    cxt.commit('setUserinfo', {})
    // 重置路由
    // resetRouter()
  },
  // 获取用户信息
  async getProfile(cxt) {
    const res = await getProfile()
    cxt.commit('setUserinfo', res.data)
    // 返回结果
    return res.data
  },
  // 登录
  async login(cxt, payload) {
    const res = await login(payload)
    // console.log(res)
    Message.success('登录成功!')
    const token = res.data
    cxt.commit('setToken', token)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

